const {
	db,
	dbCmd,
	result_success,
	result_error,
	appletInfoCollection,
	shopieCollection,
	shopieReportCollection,
	shopieUserReportCollection,
	getCommonTime,
	userCollection
} = require('../../common/constants')
module.exports = async function(params = {}) {
	const token = this.getUniIdToken()
	if (!token) {
		return result_error('登录失效,请重新登录')
	}
	let payload = await this.uniID.checkToken(token)
	if (payload.code) {
		return payload
	}
	let cUser = await userCollection.doc(payload.uid).get()
	cUser = cUser.data[0]
	let role = cUser.role[0]
	if(!cUser.app_id){
		return result_success({})
	}
	//获取当前应用
	let appletInfoData = await appletInfoCollection.doc(cUser.app_id).get()
	appletInfoData = appletInfoData.data[0]
	let cDateObj = getCommonTime()
	let cYear = cDateObj.now.year
	let cMonth = cDateObj.now.month
	let cDay = cDateObj.now.day
	let report_start_time = '00:00:00'
	let report_end_time = '23:59:59'
	let sDateTime = getCommonTime(new Date(cYear + "-" + cMonth + "-" + cDay + " " + report_start_time)).now
		.dateTime
	let eDateTime = getCommonTime(new Date(cYear + "-" + cMonth + "-" + cDay + " " + report_end_time)).now
		.dateTime
	if (appletInfoData.report_start_time && appletInfoData.report_end_time && appletInfoData.report_end_time !=
		'23:59:59') {
		let rHours = appletInfoData.report_end_time
		rHours = parseInt(rHours.split(':')[0])
		let cHours = cDateObj.now.hour
		if (cHours <= rHours) {
			let cDate = new Date()
			cDate.setDate(cDate.getDate() - 1)
			cDateObj = getCommonTime(cDate)
			cYear = cDateObj.now.year
			cMonth = cDateObj.now.month
			cDay = cDateObj.now.day
		}
	}
	let queryParams = {
		app_id: appletInfoData._id,
		shop_id: appletInfoData._id,
		year: cYear,
		month: cMonth,
		day: cDay
	};
	let shopieReportData
	if (role === 'shop_admin') {
		shopieReportData = await shopieReportCollection.where(queryParams)
			.get()
	} else {
		queryParams.share_user_id = cUser._id
		shopieReportData = await shopieUserReportCollection.where(queryParams)
			.get()
	}
	shopieReportData = shopieReportData.data
	return result_success(shopieReportData)
}